package cn.itcast.realm;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class SaasRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private ModuleService moduleService;

    @Override //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String email = token.getUsername();
        String password_page = new String(token.getPassword());
        User user = userService.findByEmail(email);
        if (user != null){
            String password_db = user.getPassword();
            if (password_db.equals(password_page)){
                //Object principal主角, Object credentials 加密后的密码, String realmName realm类名
                return new SimpleAuthenticationInfo(user,password_page,getName());
            }
        }
        return null;//此处如果返回null,则subject会报异常
    }



    @Override //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //告诉shiro有哪些权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<Module> moduleList = moduleService.findModuleBy(user);
        for (Module module : moduleList) {
            info.addStringPermission(module.getName());
        }



        return info;
    }


}
